#!/bin/sh

# 生成数据库迁移文件
echo "生成数据库迁移文件..."
python manage.py makemigrations
python manage.py makemigrations navigation

# 执行数据库迁移
echo "执行数据库迁移..."
python manage.py migrate

# 收集静态文件
echo "收集静态文件..."
python manage.py collectstatic --noinput

# 检查是否需要创建超级用户
echo "检查是否需要创建超级用户..."
USER_COUNT=$(python manage.py shell -c "from django.contrib.auth.models import User; print(User.objects.filter(is_superuser=True).count())")

if [ "$USER_COUNT" -eq "0" ]; then
    echo "创建默认管理员账号 (admin/admin)..."
    python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'admin')"
fi

# 检查是否需要初始化导航数据
echo "检查是否需要初始化导航数据..."
LINK_COUNT=$(python manage.py shell -c "from navigation.models import NavigationLink; print(NavigationLink.objects.count())")

if [ "$LINK_COUNT" -eq "0" ]; then
    echo "初始化导航数据..."
    python manage.py init_nav_data
fi

# 启动服务
if [ "$DEBUG" = "True" ]; then
    echo "以开发模式启动服务..."
    python manage.py runserver 0.0.0.0:${PORT:-8000}
else
    echo "以生产模式启动服务..."
    gunicorn website.wsgi:application --bind 0.0.0.0:${PORT:-8000} --workers ${WORKERS:-2} --timeout ${TIMEOUT:-120}
fi
